<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>双向绑定</title>
        <style>
            h3 {
                margin: 10px auto;
            }
            .wrapper { 
                padding: 10px;
                border: 1px solid blue;
                margin: 10px auto;
            }
        </style>
    </head>
    <div>

        <h3>山寨版双向绑定</h3>

        <div class="wrapper first">
            <input type="text" placeholder="请输入用户名">
        </div>

        <div class="wrapper second"></div>

        <script>

            const input = document.querySelector('input[type=text]');
            const second = document.querySelector('.second');

            /*
            class Student {
                // 可以将`#`为前缀的变量视为私有变量
                #content = 12345;
                // getter
                get content(){
                    console.log('getter');
                    return this.#content;
                }
                // setter
                set content(value) {
                    console.log('setter');
                    this.#content = value;
                    second.innerHTML = this.#content;
                    if( this.#content != input.value ) {
                        input.value = this.#content;
                    }
                } 
            }
            const stu = new Student();
            console.log( stu );
            */

            const stu = Object.create(null);
            console.log( stu );

            // Object.defineProperty(对象, 属性名, 属性描述符 )
            Object.defineProperty(stu, '_content', {
                value: '', enumerable: true, configurable: true, writable: true
            });

            // Object.defineProperty(对象, 属性名, 存取描述符)
            Object.defineProperty(stu, 'content', {
                enumerable: true,
                configurable: true,
                get() {
                    console.log('geter');
                    return stu._content;
                },
                set(value) {
                    console.log('setter');
                    stu._content = value;
                    second.innerHTML = stu._content;
                    if( stu._content != input.value ) {
                        input.value = stu._content;
                    }
                }
            });

            // 监听输入框的 input 事件
            input.addEventListener('input', evt => {
                console.log( '本次输入的字符是:', evt.data );
                let content = evt.target.value;
                console.log( '输入框中的内容是:', content );
                stu.content = content;
            }, false);
        </script>
    </div>
</html>